package com.future.mayi.activity;


import android.content.DialogInterface;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.SealConst;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.dialog.CommonDialog;
import com.future.mayi.jpush.JPushManager;
import com.future.mayi.model.UserInfoModel;
import com.future.mayi.response.LoginResponse;
import com.future.mayi.utils.BroadcastManagerUtil;
import com.future.mayi.utils.LoginApiUtils;
import com.future.mayi.utils.SharedPreferencesUtils;

import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;

public class LoginActivity extends BaseActivity {


    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.btn_wechat)
    LinearLayout btnWechat;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.ll_agreement)
    LinearLayout llAgreement;



    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_login);
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initDates() {
        if (getIntent() != null && getIntent().getBooleanExtra("squeeze", false)) {
            new CommonDialog.Builder(this)
                    .setCancelable(false)
                    .setMessage("登录信息已失效，请重新登录")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    }

    @Override
    protected void initListener() {
    }


    //Share平台


    public void thirdLogin(String platform) {
        setEnabled(false);
        LoginApiUtils api = new LoginApiUtils();
        api.setPlatform(platform);
        api.setOnLoginListener(new LoginApiUtils.OnLoginListener() {
            public boolean onLogin(String platform, int state) {
                if (state == 1) {
                    Platform platforms = ShareSDK.getPlatform(platform);
                    String id = platforms.getDb().getUserId();
//                    if (platform.equals(Wechat.NAME)) {
//                        id = platforms.getDb().get("unionid");
//                    }
                    String icon = platforms.getDb().getUserIcon();
                    String name = platforms.getDb().getUserName();
                    login(id, icon, name);
                } else if (state == 2) {
                    setEnabled(true);
                    toast("登录取消");
                } else if (state == 3) {
                    setEnabled(true);
                    toast("登录失败");
                }
                return true;
            }
        });
        api.login(this);
    }


    @SuppressWarnings("unchecked")
    private void login(final String id, final String icon, final String name) {
        setEnabled(false);
        TreeMap<String, Object> params = new TreeMap<>();
        String url = ApiCst.wxlogin;
        params.put("openid", id);
        params.put("avatar", icon);
        params.put("nickname", name);
        new HttpRequest<LoginResponse>()
                .with(this)
                .setApiCode(url)
                .addParams(params)
                .setListener(new HttpRequest.OnNetworkListener<LoginResponse>() {
                    @Override
                    public void onSuccess(LoginResponse baseResponse) {
                        setEnabled(true);
                        UserInfoModel userInfoModel = baseResponse.userInfoModel;
                        if (userInfoModel == null || TextUtils.isEmpty(userInfoModel.getMobile())) {
                            if (!TextUtils.isEmpty(id)) {
                                RegisterActivity.startActivity(LoginActivity.this, id, icon, name);
                                return;
                            }
                            return;
                        }
                        if (userInfoModel.getStatus() == 99) {
                            BroadcastManagerUtil.getInstance(mContext).sendBroadcast(SealConst.BAN);
                            return;
                        }
                        SharedPreferencesUtils.setUser(mContext, userInfoModel);
                        new JPushManager().setAlias(String.valueOf(userInfoModel.getUser_id()));
                        finish();
                    }

                    @Override
                    public void onFail(String message, LoginResponse response) {
                        if (response.returnNo == 100) {
                            if (!TextUtils.isEmpty(id)) {
                                RegisterActivity.startActivity(LoginActivity.this, id, icon, name);
                                return;
                            }
                        }
                        toast(message);
                        setEnabled(true);
                    }
                }).start(new LoginResponse());
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (App.isLogin()) {
            finish();
        } else {
            SharedPreferencesUtils.clear(getApplicationContext(), SharedPreferencesUtils.SpEnum.UserVo);
            setEnabled(true);
        }
    }


    private void setEnabled(boolean enabled) {
        if (btnWechat != null)
            btnWechat.setEnabled(enabled);
        if (enabled) {
            dissmissLoadingDialog();
        } else {
            showLoadingDialog();
        }
    }


    @OnClick({R.id.iv_close, R.id.btn_wechat, R.id.tv_phone, R.id.ll_agreement})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
            case R.id.btn_wechat:
                if (ShareSDK.getPlatform(Wechat.NAME).isClientValid()) {
                    thirdLogin(Wechat.NAME);
                } else {
                    toast("手机未安装微信");
                }
                break;
            case R.id.tv_phone:
                RegisterActivity.startActivity(this, 1);
                break;
            case R.id.ll_agreement:
                startActivity(new Intent(mContext, AgreementActivity.class));
                break;
        }
    }


}

